package b;

import a.UdpEchoServer;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86183
 * Date: 2024-04-25
 * Time: 19:09
 */

/**
 * 服务器
 * 1:读取请求并解析
 * 2:根据请求计算响应
 * 3:把响应写回到客户端
 */
public class UdpEchoServe {
     private DatagramSocket socket =null;
     public UdpEchoServe(int port) throws SocketException {
         socket = new DatagramSocket(port);
      }

    public void start() throws IOException {
        System.out.println("服务器启动!");
        while(true){
            DatagramPacket requestPakcet  = new DatagramPacket(new byte[4096],4096);
            socket.receive(requestPakcet);
            String request = new String(requestPakcet.getData(),0,requestPakcet.getLength());
            String response = process(request);
            //发送的数据报要知道发送给谁:  ip, 端口号
            DatagramPacket responsePakcet = new DatagramPacket(response.getBytes(),0,response.getBytes().length,
                    requestPakcet.getAddress(),requestPakcet.getPort());
            socket.send(responsePakcet);
            System.out.printf("[%s : %d] , req = %s , resp = %s\n",
                    requestPakcet.getAddress(),requestPakcet.getPort(),request,response);
        }
    }
    public String process(String request){
         return request;
    }

    public static void main(String[] args) throws IOException {
         UdpEchoServe udpEchoServe = new UdpEchoServe(9090);
         udpEchoServe.start();

    }
}
